package com.aischool.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aischool.common.model.SysFiles;
import com.aischool.utils.AppUtil;
import com.aischool.utils.DateUtil;
import com.aischool.utils.FileUtil;
import com.aischool.utils.ImageUtil;
import com.aischool.utils.JsonResult;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import sun.misc.BASE64Decoder;

public class FileUploadService {

	private int maxSize = 50 * 1024 * 1024;
	
	public JsonResult uploadFile(Controller controller) {
		JsonResult jr = new JsonResult();
		jr.setCode(400);

		// 图片缩放参数
        //String zoom_type = controller.getAttr("zoom_type", ""); // zoom_type: w:宽度, wh：指定宽高
        int zoom_w = AppUtil.toInt(controller.getAttr("zoom_w", ""), 0);
        int zoom_h = AppUtil.toInt(controller.getAttr("zoom_h", ""), 0);
        if (zoom_w <= 0) {
        	//zoom_type = controller.get("zoom_type", "");
        	zoom_w = controller.getInt("w", 0);
        	zoom_h = controller.getInt("h", 0);
        }
        boolean is_zoom = zoom_w>0;
        
		// 定义一堆变量
		Date Tnow = new Date();
		long startNanoTime = System.nanoTime();  
		
		int login_user_id = controller.getAttrForInt("login_user_id");
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(Tnow);
        
        File file_temp = null;
        
        String fileNameOld = "";
        String fileExt = "";
        String fileNameNew = "";
        String fileParameterName = "";             
        String fileFullNameNew = "";
        
        int fileLength = 0;
        
        String base64_data = "";
        boolean is_base64 = controller.getAttr("filemodel", "").equals("base64");

        
        if (!is_base64) {
        	List<UploadFile> filesList = null;
    		try {
    			filesList = controller.getFiles("/temp", maxSize, "utf-8");
    		} catch (Exception ex) {
    			ex.printStackTrace();
    			jr.setMsg("文件大小不能超过50M！");
    			return jr;
    		}
    		if (filesList.size() == 0) {
    			jr.setMsg("文件为空");
    			return jr;
    		}
    		
    		UploadFile uploadFile = filesList.get(0);
    		file_temp = uploadFile.getFile();

            fileNameOld = uploadFile.getFileName();
            fileExt = fileNameOld.substring(fileNameOld.lastIndexOf("."));
            fileNameNew = startNanoTime + fileExt;
            fileParameterName = uploadFile.getParameterName();
            fileFullNameNew = "/upload/" + datePath + "/" + fileNameNew;
            fileLength = (int)(file_temp.length()/1024)+1; 						// 获取文件大小 KB
        }else {
        	base64_data = controller.get("base64_data").split(",")[1];
        	fileNameOld = controller.get("filename");
            fileExt = controller.get("filetype");
            fileNameNew = startNanoTime + fileExt;
            fileParameterName = ""; 
            fileFullNameNew = "/upload/" + datePath + "/" + fileNameNew;
            fileLength = (int)(controller.getInt("filesize")/1024)+1; 						// 获取文件大小 KB
        }
		
        if(AppUtil.Upload_File_Ext.indexOf(fileExt)<0){
			jr.setMsg("不允许的文件格式！" + fileExt);
			return jr;
        }
        
        // 计算新文件名
        File targetDir = new File(PathKit.getWebRootPath() + "/upload/" + datePath);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        
        File targetFile = new File(targetDir, fileNameNew);
        int iloop = 0;
        while (targetFile.exists()) {
        	iloop++;
        	fileNameNew = startNanoTime + iloop + fileExt;
        	fileFullNameNew = "/upload/" + datePath + "/" + fileNameNew;
        	targetFile = new File(targetDir, fileNameNew);
        	if (iloop>=1000) {
    			jr.setMsg("文件已存在，请重试！");
    			return jr;
        	}
        }
        // 移动文件
        boolean bf = false;
        if (!is_base64) {
        	bf = file_temp.renameTo(targetFile);// 移动文件到指定位置
        }else {
        	bf = SaveBase64File(base64_data, PathKit.getWebRootPath() + fileFullNameNew);
        }
        
        if (!bf) {
        	jr.setMsg("文件未写入指定位置，请联系管理员！");
        	return jr;
        }else {
        	String sname = fileNameOld.replaceAll(fileExt, "");
            SysFiles infoFile = new SysFiles();
            infoFile.setFileName(sname);
            infoFile.setFileAbspath(fileFullNameNew);
            infoFile.setFileType(fileExt);
            infoFile.setFileSize(fileLength);
            infoFile.setUploadTime(DateUtil.getTimestamp());
            infoFile.setUploadUserid(login_user_id);
            infoFile.removeNullValueAttrs();
            bf = infoFile.save();
            if (!bf) {
        		jr.setMsg("插入数据库失败，请联系管理员！");
        		return jr;
            }
        }
        
        // 是否生成缩略图
        if (is_zoom && targetFile.exists() && zoom_w>0) {
        	String zoom_file_path = PathKit.getWebRootPath() + fileFullNameNew.replace(fileExt, "_"+zoom_w+"x"+zoom_h+fileExt);
        	ImageUtil.makeZoomImage(targetFile, zoom_file_path, zoom_w, zoom_h);
        }
        
        if (file_temp!=null && file_temp.exists()) {
        	file_temp.delete();
        }
            
        jr.setCode(0); // 兼容 layuieditor 
        jr.setMsg("文件上传成功！");
        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("src", "/upload/" + datePath + "/" + fileNameNew);
        map1.put("paramid", fileParameterName);
        map1.put("oldname", fileNameOld);
        map1.put("fileext", fileExt);
        map1.put("filelen", fileLength); //KB
        
        jr.setDicKV("fileurl", "/upload/" + datePath + "/" + fileNameNew);
        
        jr.setData(map1);
        
        return jr;
	}
	
	private boolean SaveBase64File(String base64str, String savepath) {   
		//对字节数组字符串进行Base64解码并生成图片  
        if (base64str == null) //图像数据为空  
            return false;  
       // System.out.println("开始解码");
        BASE64Decoder decoder = new BASE64Decoder();  
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(base64str);  
          //  System.out.println("解码完成");
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }
           // System.out.println("开始生成图片");
            //生成j p e g 图片  
            OutputStream out = new FileOutputStream(savepath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            return false;  
        }  
    }

    public JsonResult bigUpload(Controller controller) {
    	JsonResult jr = new JsonResult();
    	
    	int chunks = controller.getInt("chunks", -1);  
    	int chunk = controller.getInt("chunk", -1);
    	String param1 = controller.get(0);
        
        
        // 单文件上传
        if (StrKit.isBlank(param1) && (chunks < 0 || chunk < 0)) {
        	// 执行原上传逻辑
        	return uploadFile(controller);
        }
        
    	String md5value = controller.get("md5value", ""); 
        // 合并文件
        if (StrKit.notBlank(param1) && param1.equals("merge")) {
        	
        	return jr;
        }

        // 分块上传
    	String guid = controller.get("guid", "");    
    	String id = controller.get("id", "");  
    	String name = controller.get("name", ""); 
        String type = controller.get("type", "");  
        String lastModifiedDate= controller.get("lastModifiedDate", ""); 
        int size = controller.getInt("size", 0); 
        
        List<UploadFile> filesList = null;
		try {
			filesList = controller.getFiles("/temp", maxSize, "utf-8");
		} catch (Exception ex) {
			ex.printStackTrace();
			jr.setMsg("文件大小不能超过50M！");
			return jr;
		}
		if (filesList.size() == 0) {
			jr.setMsg("文件为空！");
			return jr;
		}
		if (StrKit.isBlank(md5value)) {
			jr.setMsg("文件md5值丢失！");
			return jr;
		}
		
		UploadFile uploadFile = filesList.get(0);
		File file_temp = uploadFile.getFile();		// 获取上传的文件，jfinal放在临时目录下
		
		String upload_root_path = PathKit.getWebRootPath() + "/upload";
        String upload_chunk_path = upload_root_path + "/chunk";
        String ext = name.substring(name.lastIndexOf("."));

        // 判断文件是否分块
        if (chunks > 0 && chunk >= 0) {
            String chunkfileName = md5value + "_" + chunk + ext;
            File chunkfile = new File(upload_chunk_path + "/" + chunkfileName);
            // 移动分块文件，并重命名
            file_temp.renameTo(chunkfile);
        }
    	
    	
    	return jr;
    }
    
    
}
